package cn.iocoder.yudao.framework.security.core.aop;

import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.security.core.service.SecurityFrameworkService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.security.access.prepost.PreAuthorize;

import javax.annotation.Resource;

import static cn.iocoder.yudao.framework.common.exception.enums.GlobalErrorCodeConstants.FORBIDDEN;
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;

@Aspect
@Slf4j
public class PreAuthorizeAspect {

    @Resource
    private SecurityFrameworkService securityFrameworkService;

    @Around("@annotation(preAuthorize)")
    public Object around(ProceedingJoinPoint joinPoint, PreAuthorize preAuthorize) throws Throwable {
        String value = preAuthorize.value();
        if (StrUtil.isNotEmpty(value)) {
            String permission = StrUtil.subBetween(value, "'");
            if (StrUtil.isNotEmpty(permission)) {
                if (!securityFrameworkService.hasAnyPermissions(permission)) {
                    throw exception(FORBIDDEN);
                }
            }
        }
        return joinPoint.proceed();
    }
}
